<template>
<div>
  <el-row style="background-color: #dadada" type="flex" align="middle">
    <el-col :span="1">
      <el-button native-type="button" icon="el-icon-arrow-left" style="border-width: 0px;background-color: #dadada" @click="backClick">返回</el-button>
    </el-col>
    <el-col :span="5" :offset="8">
      <label >{{title}}</label>
    </el-col>
  </el-row>
  <br>
  <el-row type="flex">
    <el-col :span="9">
      <el-form ref="form" :model="form" label-width="80px" :rules="rules">
        <el-form-item
          label="礼包名称"
          prop="name"
        >
          <el-input required placeholder="请输入礼包名称" v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="礼包logo">
          <image-upload ref="uploadLogo" :fileList="logoFiles" :urlList="logoUrls" :multiple="false" :limitCount="1"></image-upload>
        </el-form-item>
        <el-form-item
          label="活动日期"
          prop="daterange"
          :rules="[
            { required: true, message: '请输入活动时间区间', trigger: 'blur' }
          ]"
        >
          <el-date-picker
            value-format="yyyy-MM-dd"
            type="daterange"
            placeholder="活动开始日期"
            v-model="form.daterange"
            range-separator="至"
            start-placeholder="活动开始日期"
            end-placeholder="活动结束日期"
            style="width: 100%;">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="展示图片">
          <image-upload ref="prizeBg" :fileList="pbgFiles" :urlList="pbgUrls" :multiple="false" :limitCount="1"></image-upload>
        </el-form-item>
        <el-form-item label="礼包库存">
          <el-tooltip content="-99表示无限库存" placement="bottom" effect="light">
            <el-input placeholder="-99表示无限库存" v-model="form.stock"></el-input>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="转盘图片">
          <image-upload ref="uploadTurnplate" :fileList="turnplateFiles" :urlList="turnplateUrls" :multiple="false" :limitCount="1"></image-upload>
        </el-form-item>
        <el-form-item label="背景图片">
          <image-upload ref="bgImage" :fileList="bgFiles" :urlList="bgUrls" :multiple="false" :limitCount="1"></image-upload>
        </el-form-item>
        <el-form-item label="礼包状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="详情介绍">
          <el-input type="textarea" v-model="form.introduce"></el-input>
        </el-form-item>
      </el-form>
    </el-col>

    <el-col :span="14" :offset="1">
      <el-row>
        赞助榜单
      </el-row>
      <el-row>
        <el-transfer
          v-model="selBindBoards"
          class="transfer"
          :props="{
            key: 'id',
            label: 'title'
          }"
          filterable
          :data="boards"
          :titles="['未选榜单', '已选榜单']"
        >
        </el-transfer>
      </el-row>
      <br>
      <el-row>
        礼包奖品
      </el-row>
      <br>
      <div style="border:1px solid #c3c3c3;">
        <el-row>
          <el-table
            :data="form.prizes"
            max-height="500px"
            style="width: 100%"

          >
            <el-table-column type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="demo-table-expand">
                  <el-form-item label="礼品名称:">
                    <span>{{ props.row.name }}</span>
                  </el-form-item>
                  <el-form-item label="状态:">
                    <span>{{ showStatus(props.row) }}</span>
                  </el-form-item>
                  <el-form-item label="礼品类型:">
                    <span>{{showType(props.row)}}</span>
                  </el-form-item>
                  <el-form-item label="千分比概率:">
                    <span>{{ props.row.probability }}</span>
                  </el-form-item>
                  <el-form-item label="库存数:">
                    <span>{{ props.row.stock }}</span>
                  </el-form-item>
                  <el-form-item label="开始时间:">
                    <span>{{ props.row.startTime }}</span>
                  </el-form-item>
                  <el-form-item label="结束时间:">
                    <span>{{ props.row.endTime }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column
              class="tableCol"
              align="center"
              label="序号"
              type="index"
              >
            </el-table-column>
            <el-table-column
              class="tableCol"
              align="center"
              label="礼包名称"
              prop="name"

            >
            </el-table-column>
            <el-table-column
              align="center"
              label="礼包类型"

              prop="type"
              :formatter="showType"
            >
            </el-table-column>
            <el-table-column
              align="center"
              label="状态"

              prop="status"
              :formatter="showStatus"
            >
            </el-table-column>

            <el-table-column
              label="操作"
              align="center"
            >
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
<!--                <el-button-->
<!--                  size="mini"-->
<!--                  type="danger"-->
<!--                  @click="handleDelete(scope.$index, scope.row)">上下架</el-button>-->
              </template>
            </el-table-column>
          </el-table>
        </el-row>
        <br>
        <el-row>
          <el-button @click="addPrize">新增礼品</el-button>
        </el-row>
        <br>
      </div>


    </el-col>

  </el-row>

  <el-row type="flex" justify="center">
    <el-col>
      <el-button type="primary" :loading="loading" @click="onSubmit">确定</el-button>
      <el-button type="info" @click="cancel" plain >取消</el-button>

    </el-col>
  </el-row>


</div>
</template>

<script>
  import ImageUpload from '../Common/ImageUpload'
  export default {
    name: 'AddCoupon',
    data(){
      return{
        title:'新增礼包',
        couponId:this.$route.query.couponId,

        loading: false,
        logoFiles:[],
        logoUrls:[],

        pbgFiles:[],
        pbgUrls:[],

        turnplateFiles:[],
        turnplateUrls:[],

        bgFiles:[],
        bgUrls:[],

        boards:[],
        selBindBoards:[],
        bindBoards:[],
        form: {
          bgImage: '',
          boardIds: [],
          createTime: '',
          endTime: '',
          id: 0,
          introduce: '',
          logo: '',
          merchantId: 0,
          name: '',
          prizeBg: '',
          prizeTurnplate: '',
          relatedBoards: [],
          startTime: '',
          status: 1,
          stock: -99,
          daterange:[],

          prizes:[]
        },
        prizes:[],
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' }
          ],
          startTime: [
            { required: true, message: '请选择开始日期', trigger: 'change' }
          ],
          endTime: [
            { required: true, message: '请选择结束', trigger: 'change' }
          ]

        }
      }
    },
    components:{
      ImageUpload
    },
    mounted(){
      if (this.couponId > 0){
        this.title = '编辑礼包'
        this.loadCoupon()
      }
      this.loadNullBindBoards()

      let str = sessionStorage.getItem('localAddPrize')
      let prize = JSON.parse(str)
      this.prizes = this.prizes.concat(prize)
      this.form.prizes = this.form.prizes.concat(prize)
    },
    methods:{
      // private Method
      showType(prize){
        // 1-红包2-1分购3-谢谢参与4:自定义',
        switch (prize.type) {
          case 1:
            return '红包';
          case 2:
            return '1分购';
          case 3:
            return '谢谢参与';
          default:
            return '其他';
        }
      },
      showStatus(prize){
        // 1-红包2-1分购3-谢谢参与4:自定义',
        switch (prize.status) {
          case 0:
            return '下架';
          case 1:
            return '上架';
          default:
            return '其他';
        }
      },
      handleEdit(index, prize) {
        this.$router.push({
          name:'addPrize',
          query:{
            prizeId:prize.id,
            giftId:this.form.id
          }
        })
      },
      handleDelete(index, prize) {
        if (this.form.prizes.length < 2){
          this.$message({
            type:'info',
            message:"奖品个数不能为空"
          })
          return
        }
        return this.$confirm("是否删除次奖品").then(() => {
          this.getAxios('giftCouponPrize/delete',{
            id:prize.id
          }).then(() => {
            this.$message({
              type:'success',
              message:"删除成功"
            })
          }).catch(error => {
            this.$message({
              type:'info',
              message:error.msg
            })
          })
        }).catch(() =>{

        })


      },
      onSubmit(){
        this.$refs.form.validate((valid) => {
          if (valid) {
            if (this.selBindBoards.length < 1){
              this.$message({
                type:'info',
                message:'请选择礼包赞助的榜单'
              })
              return false;
            }
            if (this.form.prizes.length < 1){
              this.$message({
                type:'info',
                message:'请添加关联礼品'
              })
              return false;
            }
            this.submit()
          } else {
            return false;
          }
        });
      },
      cancel(){
        return this.$confirm("是否取消此次操作").then(() => {
          this.backClick()
        }).catch(() =>{

        })
      },
      // network
      loadCoupon(){
        this.getAxios('giftCoupon/load',{
          id:this.couponId
        }).then(res => {
          let data = res.data
          let coupon = data.coupon
          this.form = coupon
          this.form.daterange = [coupon.startTime, coupon.endTime]
          let bindBoards = coupon.bindBoards
          for (let i = 0, len = bindBoards.length; i < len; i++) {
            let board = bindBoards[i]
            this.selBindBoards = this.selBindBoards.concat(board.id)
          }
          this.boards = this.boards.concat(coupon.bindBoards)


          if (!this.isEmpty(coupon.logo)){
            let obj = new Object();
            obj.url = coupon.logo;
            obj.name = 'logo'
            this.logoFiles.push(obj);
            this.logoUrls.push({
              url:coupon.logo
            })
          }

          if (!this.isEmpty(coupon.prizeBg)){
            let obj = new Object();
            obj.url = coupon.logo;
            obj.name = 'logo'
            this.pbgFiles.push(obj);
            this.pbgUrls.push({
              url:coupon.logo
            })
          }

          if (!this.isEmpty(coupon.prizeTurnplate)){
            let obj = new Object();
            obj.url = coupon.logo;
            obj.name = 'logo'
            this.turnplateFiles.push(obj);
            this.turnplateUrls.push({
              url:coupon.logo
            })
          }

          if (!this.isEmpty(coupon.bgImage)){
            let obj = new Object();
            obj.url = coupon.logo;
            obj.name = 'logo'
            this.bgFiles.push(obj);
            this.bgUrls.push({
              url:coupon.logo
            })
          }

        }).catch(error => {
          this.$message({
            type:'info',
            message:error.msg
          })
        })
      },
      loadNullBindBoards(){

        this.getAxios('giftCoupon/nullBindBoards',{

        }).then(res => {

          this.boards = res.data.concat(this.bindBoards)
          // this.boards = res.data.concat(this.selBindBoards)
        }).catch(error => {
          this.$message({
            type:'info',
            message:error.msg
          })
        })
      },
      submit(){
        if (this.logoUrls.length > 0){
          let obj = this.logoUrls[0]
          this.form.logo = obj.url
        }
        if (this.pbgUrls.length > 0){
          let obj = this.pbgUrls[0]
          this.form.prizeBg = obj.url
        }
        if (this.turnplateUrls.length > 0){
          let obj = this.turnplateUrls[0]
          this.form.prizeTurnplate = obj.url
        }
        if (this.bgUrls.length > 0){
          let obj = this.bgUrls[0]
          this.form.bgImage = obj.url
        }

        this.form.startTime = this.form.daterange[0]
        this.form.endTime = this.form.daterange[1]
        this.form.daterange = []

        this.form.id = this.couponId
        let boardIds = this.selBindBoards.join(',')
        this.form.boardIds = boardIds

        let url = this.couponId > 0 ? 'giftCoupon/update' : 'giftCoupon/insert'
        let params = this.deepCopy(this.form)
        params.prizes = JSON.stringify(this.form.prizes)
        this.getAxios(url, params).then(res => {
          this.$message({
            type:'success',
            message:'操作成功'
          })
          this.backClick()
        }).catch(error => {
          this.$message({
            type:'info',
            message:error.msg
          })
        })
      },
      // navigation
      addPrize(){
        this.$router.push({
          name:'addPrize',
          query:{
            giftId:this.form.id
          }
        })
      },
      backClick(){
        sessionStorage.setItem('localAddPrize', '[]')
        this.$router.back()
      }
    },

  }
</script>

<style scoped>
  /deep/.transfer .el-transfer-panel__item .el-checkbox__input{
    left: 15px;
  }
  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 90px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
  }
  .tableCol{
  }
</style>
